package com.wlyy.bcwlw.common.utils;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import com.rework.joss.persistence.convention.utils.ConventionUtils;
import com.wlyy.bcwlw.sys.SecurityConst;






public class SecurityUtil {

	private static final Logger logger = LogManager.getLogger(SecurityUtil.class);
	private static final CustomPrivateKeyCipher SECUIRITY_KEY_CIPHER = new CustomPrivateKeyCipher("$%^&%$_-$%%$12qazw2sxQAZX0000bc");
	private static final String ENCODE_USERID_TEMPLATE = "time${time}***userId:${userId}***time${time}";
	
	/**
	 * 
	* @Title. getClientIP
	* @Description. 获取客户端ip
	* @param request
	* @return String
	* @exception.
	 */
	public static String getClientIP(HttpServletRequest request) {
		if (request == null)
			return "";
		String ip = request.getHeader("x-forwarded-for");
		if (StringUtils.isEmpty(ip)) {
			ip = request.getHeader("Proxy-Client-IP");
		}
		if (StringUtils.isEmpty(ip)) {
			ip = request.getHeader("WL-Proxy-Client-IP");
		}
		if (StringUtils.isEmpty(ip)) {
			ip = request.getRemoteAddr();
		}
		String[] ips = new String[0];
		if (StringUtils.isNotEmpty(ip))
			ips = ip.split(",");

		for (int i = 0; i < ips.length; i++) {
			if (!"unknown".equalsIgnoreCase(ips[i])) {
				ip = ips[i];
				break;
			}
		}
		return ip;
	}


	/**
	 * 
	* @Title. getClientExplorer
	* @Description. 客户端浏览器内容
	* @param request
	* @return String
	* @exception.
	 */
	public static String getClientExplorer(HttpServletRequest request) {

		String explorer = "未知";   
		String info = request.getHeader("user-agent");
		if(StringUtils.isEmpty(info)) {
			return null;
		}

		Pattern pattern = Pattern.compile("");   
		Matcher matcher;   

		if(info.indexOf("MSIE") != -1){   

			explorer = "IE"; //微软IE   
			pattern = Pattern.compile(explorer + "\\s([0-20.]+)");   

		}else if(info.indexOf("Firefox") != -1){   

			explorer = "Firefox"; // 火狐
			pattern = Pattern.compile(explorer + "\\/([0-9.]+)");   

		}else if(info.indexOf("Chrome") != -1){   

			explorer = "Chrome"; //Google   
			pattern = Pattern.compile(explorer + "\\/([0-9.]+)");   

		}else if(info.indexOf("Opera") != -1){   

			explorer = "Opera"; //Opera   
			pattern = Pattern.compile("Version\\/([0-9.]+)");   

		}else if(info.indexOf("Safari") != -1){   

			explorer = "Safari"; //Safari   
			pattern = Pattern.compile("Version\\/([0-9.]+)");   
		}      


		matcher = pattern.matcher(info);   


		try {
			if (matcher.find( 1 )) {
				explorer += " " + matcher.group(1);
			}
		} catch (Exception e) {
			logger.error("解析" + info + "失败");
		}

		return explorer;  
	}
	
	/**
	 * 
	* @Title. encodeCookieUserId
	* @Description.  加密后的用户id
	* @param userId
	* @return String
	* @exception.
	 */
	public static String encodeCookieUserId(String userId) {
		if(StringUtils.isEmpty(userId) || SecurityConst.ANONYMOUS_ID.equals(userId)) {
			return userId;
		}
		return SECUIRITY_KEY_CIPHER.encrypt(TemplateUtil.velocity(ENCODE_USERID_TEMPLATE, 
				ConventionUtils.toMap("time", System.currentTimeMillis(), "userId", userId)));
	}
	
	/**
	 * 
	* @Title. decodeCookieUserId
	* @Description. 解密后的用户id
	* @param userCookieId
	* @return String
	* @exception.
	 */
	public static String decodeCookieUserId(String userCookieId) {
		if(StringUtils.isEmpty(userCookieId)) {
			return userCookieId;
		}
		String[] decodedUserIdArray = 
				StringUtils.splitByWholeSeparator(SECUIRITY_KEY_CIPHER.decrypt(userCookieId), "***");
		for (String str : decodedUserIdArray) {
			if(StringUtils.startsWith(str, "userId:")) {
				return StringUtils.removeStart(str, "userId:");
			}
		}
		return userCookieId;
	}
	
}
